package edu.fub.pub2search.app;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * A single cache for the application. It uses the singleton pattern to ensure
 * that only one instance of the class will exist in a given application.
 * 
 * @author Josef
 */
public class SingleCache {
	
	/** contains the cache data of pubs */
	private List<Map<String, String>> cacheContent;
	
	/** Id for pub on-select */
	private int onSelectId;
	
	/**
	 *  A private Constructor prevents any other class from instantiating
	 */
	private SingleCache() { }

	/**
	 * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
	 * or the first access to SingletonHolder.INSTANCE, not before.
	 */
	private static class SingletonHolder { 
		private final static SingleCache INSTANCE = new SingleCache();
	}
	
	/** 
	 * Static 'instance' method 
	 */
	public static SingleCache getInstance() { 
		return SingletonHolder.INSTANCE;
	}
	
	/**
	 * Get the cache which is protected by this singleton class.
	 * 
	 * @return the cache.
	 */
	public List<Map<String, String>> getCacheContent() {  
		
		return cacheContent;
	}
	
	/**
	 * Set the cache to be protected by this singleton class.
	 * 
	 * @param cacheContent the cache.
	 */
	public void setCacheContent(List<Map<String, String>> cacheContent) {
		
		this.cacheContent = cacheContent;
	}
	
	/**
	 * Get one pub record that is being selected.
	 * 
	 * @return a pub record.
	 */
	public Map<String, String> getCacheContentOnSelect() {
				
		Map<String, String> pub = null;
		int pubId = 0;
		
		// search from all pub records
		Iterator<Map<String, String>> iter = cacheContent.iterator();
		while(iter.hasNext()) {
			
			pub = iter.next();	// get one record
			pubId = Integer.parseInt(pub.get("id"));  // get its id as int
			
			if (pubId == onSelectId) {	// compare if this record is the selected one
				return pub;
			}
		}
		
		return null;
	}
	
	/**
	 * Set the selected pub id.
	 * 
	 * @param onSelectId The pub id that is being selected.
	 */
	public void setCacheContentOnSelect(int onSelectId) {
		
		this.onSelectId = onSelectId;
	}
}
